<template>
  <div class="app-container">
    <el-card>
      <el-row class="row">
        <el-col :span="3">
          <el-button type="primary" size="mini" @click="add">添加</el-button>
        </el-col>
        <el-col :span="6" :offset="7">
          <span class="table-tit">收入记录</span></el-col
        >
        <el-col :span="6" :offset="5"
          ><el-button
            :loading="downloadLoading"
            style="margin: -5px 0 0 20px"
            type="primary"
            icon="el-icon-document"
            size="mini"
            @click="handleDownload"
          >
            以Excel文件格式导出
          </el-button></el-col
        >
      </el-row>
      <el-row>
        <el-col :span="24">
          <el-table
            :default-sort="{ prop: 'time', order: 'descending' }"
            stripe
            v-loading="listLoading"
            :data="list"
            element-loading-text="Loading..."
            border
            fit
            highlight-current-row
          >
            <el-table-column align="center" label="序号" width="130">
              <template slot-scope="scope">
                {{ scope.row.id }}
              </template>
            </el-table-column>
            <el-table-column label="￥收入金额" width="140" align="center">
              <template slot-scope="scope">
                {{ scope.row.price }}
              </template>
            </el-table-column>
            <el-table-column label="收入类别" align="center" width="170">
              <template slot-scope="scope">
                <el-tag effect="dark">{{ scope.row.category }}</el-tag>
              </template>
            </el-table-column>
            <!-- 默认是当前时间 -->
            <el-table-column label="收入时间" prop="time" sortable align="center">
              <template slot-scope="scope">
                {{ scope.row.time | formatDate() }}
              </template>
            </el-table-column>
            <el-table-column label="操作" align="center" width="200">
              <template slot-scope="scope">
                <el-button size="mini" @click="edit(scope.row)">编辑</el-button>
                <el-button
                  size="mini"
                  type="danger"
                  @click="handleDelete(scope.row)"
                  >删除</el-button
                >
              </template></el-table-column
            >
          </el-table></el-col
        ></el-row
      >
      <el-row class="row" style="margin-top: 10px">
        <el-col :span="19"
          ><el-pagination
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
            style="text-align: center"
            :current-page="page"
            :page-sizes="[5,10]"
            :page-size="limit"
            background
            :total="total"
            layout="total,prev, pager, next, jumper,->,sizes"
          >
          </el-pagination
        ></el-col>
        <el-col :span="6" :offset="1">收入总计：{{ totalMoney }}元</el-col>
      </el-row>
      <el-dialog
        :title="condition == '修改' ? '修改收入明细' : '添加收入明细'"
        :visible.sync="dialogVisible"
        width="30%"
      >
        <el-form label-width="80px" :model="editForm" :rules="rule" ref="form">
          <el-form-item label="收入类别" prop="category">
            <el-select
              v-model="editForm.category"
              placeholder="请选择分类"
              style="width: 100%"
            >
              <el-option
                :label="item.label"
                :value="item.value"
                v-for="item in categoryList"
                :key="item.value"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="金额" prop="price">
            <el-input v-model.number="editForm.price"></el-input>
          </el-form-item>
          <el-form-item label="收入时间" prop="time">
            <el-date-picker
              format="yyyy年M月d日"
              value-format="yyyy-M-d"
              v-model="editForm.time"
              align="right"
              type="date"
              placeholder="选择日期"
              :picker-options="pickerOptions"
            >
            </el-date-picker>
          </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
          <el-button @click="dialogVisible = false" size="mini"
            >取 消</el-button
          >
          <el-button type="primary" size="mini" @click="updateOrAdd"
            >确 定</el-button
          >
        </span>
      </el-dialog>
    </el-card>
  </div>
</template>
<script>
import { ConsoleWriter } from "istanbul-lib-report";

export default {
  name: "Income",
  data() {
    return {
      all: null,
      list: null,
      mon: "",
      listLoading: false,
      downloadLoading: false,
      limit: 5,
      page: 1,
      total: 0,
      dialogVisible: false,
      editForm: {
        id: 0,
        category: "",
        time: "",
        price: 0,
      },
      categoryList: [
        { label: "工资收入", value: "工资收入" },
        { label: "利息收入", value: "利息收入" },
        { label: "投资收入", value: "投资收入" },
        { label: "兼职收入", value: "兼职收入" },
        { label: "中奖收入", value: "中奖收入" },
        { label: "废旧物品", value: "废旧物品" },
        { label: "微信红包", value: "微信红包" },
        { label: "其他收入", value: "其他收入" },
      ],
      pickerOptions: {
        disabledDate(time) {
          return time.getTime() > Date.now();
        },
        shortcuts: [
          {
            text: "今天",
            onClick(picker) {
              picker.$emit("pick", new Date());
            },
          },
          {
            text: "昨天",
            onClick(picker) {
              const date = new Date();
              date.setTime(date.getTime() - 3600 * 1000 * 24);
              picker.$emit("pick", date);
            },
          },
          {
            text: "一周前",
            onClick(picker) {
              const date = new Date();
              date.setTime(date.getTime() - 3600 * 1000 * 24 * 7);
              picker.$emit("pick", date);
            },
          },
        ],
      },
      condition: "",
      rule: {
        category: [
          { required: true, message: "收入分类不能为空", trigger: "change" },
        ],
        time: [{ required: true, message: "请选择时间", trigger: "change" }],
        price: [{ required: true, message: "请选择金额", trigger: "blur" }],
      },
    };
  },
  filters: {
      formatDate: function (value) {
        var dt = new Date(value);
        console.log(dt)
        let year = dt.getFullYear();
        let month = dt.getMonth() + 1;
        let date = dt.getDate();
        return `${year}年${month}月${date}日`;
      },
    },
  computed: {
    totalMoney() {
      let sum = 0;
      //  Cannot read property 'forEach' of null"
      if (this.all) {
        this.all.forEach((item) => {
          sum += parseInt(item.price);
        });
      }
      return sum;
    },
  },
  mounted() {
    this.fetchData();
    this.getAll();
  },
  methods: {
    async fetchData() {
      this.listLoading = true;
      // methods里面是不能看到data的 需要通过this解析
      const { page, limit } = this;
      let re = await this.$API.income.getList(page, limit);
      if (re.status == 200) {
        this.list = re.data;
        this.listLoading = false;
      }
    },
    async getAll() {
      let re = await this.$API.income.getList(1, 100);
      if (re.status == 200) {
        this.all = re.data;
        this.total = re.data.length;
      }
    },
    handleDownload() {
      this.downloadLoading = true;
      import("@/vendor/Export2Excel").then((excel) => {
        const tHeader = ["序号", "收入类别", "￥收入金额", , "收入时间"];
        const filterVal = ["id", "category", "price", "time"];
        const all = this.all;
        const data = this.formatJson(filterVal, all);
        excel.export_json_to_excel({
          header: tHeader,
          data,
          filename: "excel-list",
          autoWidth: true,
          bookType: "xlsx",
        });
        this.downloadLoading = false;
      });
    },
    formatJson(filterVal, jsonData) {
      return jsonData.map((v) =>
        filterVal.map((j) => {
          if (j === "timestamp") {
            return parseTime(v[j]);
          } else {
            return v[j];
          }
        })
      );
    },
    handleSizeChange(limit) {
      this.limit = limit;
      this.fetchData();
    },
    handleCurrentChange(page) {
      this.page = page;
      this.fetchData();
    },
    edit(row) {
      this.dialogVisible = true;
      this.editForm = { ...row };
      this.condition = "修改";
    },
    // 根据是否传入的参数是一个还是两个来决定是修改还是增加 或者设定一个变量存储状态
    updateOrAdd() {
      this.$refs.form.validate(async (valid) => {
        if (valid) {
          const { editForm } = this;
          this.dialogVisible = false;
          let re = null;
          if (this.condition == "修改") {
            re = await this.$API.income.updateListItem(editForm.id, editForm);
          } else {
            re = await this.$API.income.addListItem(editForm);
          }
          // 修改成功返回的status是200 statusText是ok
          // 添加成功返回的status是201 statusText是created
          if (re.status == 200 || re.status == 201) {
            this.$message.success(`${this.condition}成功`);
          }
          this.fetchData();
          this.getAll();
        } else this.$message.error(`${this.condition}失败`);
      });
    },
    async handleDelete(row) {
      this.$confirm("此操作将永久删除该文件, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(async () => {
          let re = await this.$API.income.deleteListItem(row.id);
          if (re.status == 200) {
            this.$message.success("删除成功");
          }
          this.fetchData();
          this.getAll();
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除",
          });
        });
    },
    add() {
      this.dialogVisible = true;
      this.editForm = {
        id: 0,
        category: "",
        time: "",
        price: 0,
      };
      this.condition = "添加";
    },
  },
};
</script>
<style>
.app-container {
  background-color: whitesmoke;
}

.radio-label {
  font-size: 14px;
  color: #606266;
  line-height: 40px;
  padding: 0 12px 0 30px;
}

.row {
  height: 30px;
  display: flex;
  align-items: center;
  margin-bottom: 10px;
}
</style>
